/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections;
using System.Web.Mail;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Configuration;
using System.Text.RegularExpressions;

namespace FourRoads.Links
{
	using DataProvider;
	/// <summary>
	/// Summary description for ResLInkEmails.
	/// </summary>
	internal class ResLinkEmails : Emails 
	{
		public static void LinkTracking(ResLinkLink link , ResLinkSection section)
		{
			SectionTracking(link, new EnquePostEmails(CreateNotficationPost), CreateLinkFormatList(section.Name, link.Subject , link.User.Username , section.SectionID) );
		}

		public static void LinkCommentTracking(ResLinkComments comment ,ResLinkLink link  ,  ResLinkSection section)
		{
			SectionTracking(comment, new EnquePostEmails(CreateNotficationPost), CreateLinkFormatList(section.Name, link.Subject , comment.User.Username , section.SectionID ) );
		}

		public static void SectionTracking(ResLinkSection section , ResLinkSection newSection)
		{
			SectionTracking(section.SectionID , CSContext.Current.User , new EnquePostEmails(CreateNotficationPost), CreateSectionFormatList(CSContext.Current.User.Username , section , newSection) );
		}

		public static void LinkApproved (Post link) 
		{
			LinkPostModeration (link , "ResLinkApproved","" ); 
		}

		public static void LinkCommentApproved (Post link , Post comment) 
		{
			LinkPostModeration (comment , "ResLinkCommentApproved" ,"" ); 
		}

		public static void LinkDeleted (Post link) 
		{
			 LinkPostModeration (link , "ResLinkDeleted" ,"" ); 
		}

		public static void LinkCommentDeleted  (Post link , Post comment , string reason) 
		{
			 LinkPostModeration (comment , "ResLinkCommentDeleted" ,  reason); 
		}

		private static void LinkPostModeration (Post post, string type , string reason) 
		{
			if (post == null)
				return;

			// Make sure we can send the email
			if (!CanSend(post.User))
				return;

			EnqueuEmail(CreateModerationPost(post, type , CSContext.Current.User , post.User , reason ));
		}

		private static MailMessage CreateModerationPost(Post post , string type , User moderatedBy ,User userTo , string reason)
		{	
			if (userTo.IsAnonymous || CSContext.Current.User.IsAnonymous)
				return null;

			/*SiteName , adminemailfrom , subject , PostUrl , Moderator , DeleteReasons */
			MailMessage email = GenericEmail(type,userTo,null,null,false,userTo.EnableHtmlEmail);
			
			email.From = GenericEmailFormatter(email.From, userTo, post  ,userTo.EnableHtmlEmail);
			email.Body = GenericEmailFormatter(email.Body, userTo, post,userTo.EnableHtmlEmail);
			email.Subject = GenericEmailFormatter(email.Subject, userTo, post,userTo.EnableHtmlEmail);

			email.To = userTo.Email;

			email.Body = email.Body.Replace("[DeleteReasons]", reason);
			email.Body = email.Body.Replace("[Moderator]", moderatedBy.Username);

			if (post != null)
			{
				string postbody = string.Empty;
				// if the user doesn't want HTML and the post is HTML, then strip it
				if (!userTo.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
					postbody = Emails.FormatHtmlAsPlainText(post.FormattedBody);
				else
					postbody =  post.FormattedBody;			

				email.Body = FormatList.Format(email.Body, "postbody", postbody);
			}

			return email;
		}	

		private static FormatList CreateSectionFormatList(string userName , ResLinkSection section , ResLinkSection newSection)
		{	/*
			* sectionName , postedBy , postLink , 
			*/
			FormatList list = new FormatList();

			list.Add("sectionName", section.Name);
			list.Add("newSectionName", newSection.Name);
			list.Add("postedBy", userName);
			list.Add("postLink",  Globals.FullPath(ResLinkUrls.Instance().ViewSection(section.SectionID)));
	
			return list;
		}

		private static FormatList CreateLinkFormatList(string sectionName , string title , string userName , int sectionID)
		{	/*
			* sectionName , postedBy , postLink , 
			*/
			FormatList list = new FormatList();

	 		list.Add("sectionName", sectionName);
			list.Add("linkTitle", title);
			list.Add("postedBy", userName);
			list.Add("postLink",  Globals.FullPath(ResLinkUrls.Instance().ViewSection(sectionID)));
	
			return list;
		}

		private static MailMessage CreateNotficationPost(Post post, User user, FormatList formats)
		{
			string emailType = string.Empty;

			//Its a new child section
			if(post == null)
			{
				emailType = "ResLinkSectionNotify";
			}
			else
			{
				if(post.PostLevel != 0)
				{
					emailType = "ResLinkCommentNotify";

					if (post.IsApproved == false)
						return null;
				}
				else
				{
					emailType = "ResLinkNotify";

					if (post.IsApproved == false)
						return null;
				}
			}

			MailMessage email = GenericEmail(emailType,user,null,null,false,user.EnableHtmlEmail);
			
			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;

			if (post != null)
			{
				string postbody = string.Empty;
				// if the user doesn't want HTML and the post is HTML, then strip it
				if (!user.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
					postbody = Emails.FormatHtmlAsPlainText(post.FormattedBody);
				else
					postbody =  post.FormattedBody;			

				email.Body = FormatList.Format(email.Body, "postbody", postbody);
			}

			return email;
		}

		#region Section Tracking Without Post
		/// <summary>
		/// Based on the postID, this method will retrieve subscribers to the post and section.
		/// It will then create a unique list between them and call the method supplied vai the 
		/// EnquePostEmails delegate
		/// </summary>
		/// <param name="post">Post to send</param>
		/// <param name="epm">Method used to Enque the email</param>
		protected static void SectionTracking(int sectionID , User currentUser , EnquePostEmails epm, FormatList formats)
		{
			if (currentUser == null)
				return;

			//Iterate up the sections as tracking is done in a tree like fasion

			Hashtable sectionSubscribers = GetEmailsTrackingSectionBySectionID (sectionID);

			foreach (string email in sectionSubscribers.Keys) 
			{
				User subscriber = sectionSubscribers[email] as User;
				// Make sure we don't send an email to the user that posted the message
				//			
				if (subscriber.Email != currentUser.Email) 
				{
					EnqueuEmail(epm(null,subscriber,formats));
				}
			}
		}

		protected static Hashtable GetEmailsTrackingSectionBySectionID(int sectionID) 
		{
			ResLinkDataProvider dp = ResLinkDataProvider.Instance();

			return dp.GetEmailsTrackedBySectionID(sectionID);
		}

		#endregion
	}
}
